package test3;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式三:实现callable接口
// 1 Callable<Boolean> Boolean：返回值类型
// 2 可以抛出异常
public class Testcallable implements Callable<Boolean> {
    private String url;
    private String fileName;

    public Testcallable(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    @Override
    public Boolean call() throws Exception {
        WebDownLoader.downloader(url, fileName);
        System.out.println("succes download:" + fileName);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestThread3_2 t1 = new TestThread3_2("https://img0.baidu.com/it/u=3021883569,1259262591&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1692378000&t=c466fc9fc82d323f075a38cbb7c6c77c", "1.png");
        TestThread3_2 t2 = new TestThread3_2("https://img1.baidu.com/it/u=3663508195,2907650417&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1692378000&t=9f11a3e494efccd0dad4d4ce8fd1d627", "2.png");
        TestThread3_2 t3 = new TestThread3_2("https://img0.baidu.com/it/u=3870526223,1678892290&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1692378000&t=810e3a8e26d36ee9e63a6ee9118a0398", "3.png");

        // 创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> result1 = (Future<Boolean>) ser.submit(t1);
        Future<Boolean> result2 = (Future<Boolean>) ser.submit(t2);
        Future<Boolean> result3 = (Future<Boolean>) ser.submit(t3);
        //获取结果
        boolean r1 = result1.get();
        boolean r2 = result2.get();
        boolean r3 = result3.get();
        // 关闭服务
        ser.shutdownNow();

    }
}

//下载器
class webDownloader {
    //下载方法
    public static void downloader(String url, String fileName) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Io异常, downloader方法出现问题");
        }
    }
}
